<?php
/**
 * Class to do common Email campaign functions
 *
 * @copyright   2010 Ricca Group, Inc.
 * @author      Mark Mitchell <mmitchell@riccagroup.com>
 **/
class EmailCampaignComponent {
       
	/**
	 * The conrtoller that is using this component
	 *
	 * @var	object
	 */
	private $controller = null;    
    
	/**
	 * List of components this component uses
	 * @var array
	 */
	public $components = array('OemproApi'); 
    
    /**
     * Oempro user
     * @var string
     */
    private $_oemProUser = 'username';
    
    /**
     * Oempro password
     * @var string
     */
    private $_oemProPass = 'password';
    
	/**
	 * API session ID
	 * @var string
	 */
	private $sessionID = null;
	
	/**
	 * Last Error result string
	 * @var string
	 */
	private $lastErrorResult;
		
	/**
     * The Startup function for our controller, that's where we initiliaze
     *
     * @param   object      $controller
     * @return  null
     */
    public function startup(&$controller) {
        $this->controller = &$controller;
		
		// When being called from a Shell controllers are not initalized
		if(!isset($this->OemproApi)) {
			App::import('Component', 'OemproApi');
			$this->OemproApi = new OemproApiComponent();
		}		
		// Startup the oempro API component 
		$this->OemproApi->startup($controller);
    }
	
	/**
	 * Return the last error result
	 *
	 * @return string	Error result
	 */
	public function lastError() {
		return $this->lastErrorResult;
	}
	
	/**
	 * Get the API credentials being used
	 * 
	 * @return array('user' => user, 'pass' => pass);
	 */
	public function getAPICredentials() {
		return array('user' => $this->_oemProUser,
					 'pass' => $this->_oemProPass);
	}
		
	/**
	 * Log into oempro API
	 * ok to call multiple times as it onl logs in once
	 *
	 * @return	boolean 	True on successfull login
	 */
	public function APILogIn() {
		if ( ! empty($this->sessionID)) {
			return true; // Already logged in
		}
		// Log in 
		$token = $this->OemproApi->userLogin(array('Username' => $this->_oemProUser,
												   'Password' => $this->_oemProPass));
		if (! $token
			|| empty($token->Success)) {
			$this->lastErrorResult = $this->OemproApi->lastError();
            return false;
        }
		$this->sessionID = $token->SessionID;
		return true;
	}
	
	/**
	 * Add email addresses to the global supression list
	 *
	 * @param	integer		$listID			Unsubscribe List To import data to
	 * @param	string		&$importData	CSV data string ref (ref cause it can be big string)
	 * @param	array		$fieldIds		List of custom field IDs
	 * @param	array		$options		Import options to pass to API
	 * @return	boolean		True on sucess, otherwise false
	 */
	public function addEmailsToGlobalSupressionList($listID, &$importData, $fieldIds, $dataOptions = array(), $options = array()) {
		$import1Options = array_merge(array('FieldTerminator' => ',',
											'FieldEncloser' => '"'), $dataOptions);
		$import2Options = array_merge(array('AddToGlobalSuppressionList' => 'true',
											'AddToSuppressionList' => 'false',
											'TriggerBehaviors' => 'false'), $options);
		$importStep1 = 
			$this->OemproApi->subscribersImport(array_merge(
												array('ListID' => $listID,
													  'ImportStep' => 1,
													  'ImportType' => 'Copy',
													  'ImportData' => &$importData,
													  ), $import1Options));
			
		if ( ! $importStep1
			|| empty($importStep1->Success)
			|| empty($importStep1->ImportFields)) {
			$this->lastErrorResult =  "OemproApi subscribersImport step 1 failed";
				return false;
		}
		// Import step 2	
		$importStep2 = 
			$this->OemproApi->subscribersImport(array_merge(
												array('ListID' => $listID,
													  'ImportID' => $importStep1->ImportID,
													  'ImportStep' => 2,
													  'MappedFields' => array('FIELD1' => 'EmailAddress',)
													), $import2Options));
		if ( ! $importStep2
			|| empty($importStep2->Success)) {
			$this->lastErrorResult =  "OemproApi subscribersImport step 2 failed";
				return false;
		}
		return true;
	}
		
		
	/**
	 * Remove an email addresses from the global supression list
	 *
	 * @param	integer		$listID			Unsubscribe List To import data to
	 * @param	string		&$importData	CSV data string ref (ref cause it can be big string)
	 * @param	array		$fieldIds		List of custom field IDs
	 * @param	array		$options		Import options to pass to API
	 * @return	boolean		True on sucess, otherwise false
	 */
	public function removeEmailsFromGlobalSupressionList($emails) {
		$subscriberIds = array(); // List of subscriber IDs to remove
		foreach ($emails as $e) {
			// Find the subsriber
			$er = $this->OemproApi->subscriberGet(array('EmailAddress'  => $e,
														'ListID' => 0,
														'Suppressed' => true));
			// If not found in global supression list then continue
			if ( ! $er
				|| empty($er->Success)) {
				continue;
			} else {
				$subscriberIds[] = $er->SubscriberInformation->SuppressionID;
			}
		}
		// Remove the subscribers we found
		$r = $this->OemproApi->subscribersDelete(array('Suppressed' => true, 'SubscriberListID' => 0, 'Subscribers' => implode(',',$subscriberIds)));
		if ( ! $r
			|| empty($r->Success)) {
			return false;
		} else {
			return true;
		}
	}		
	
	/**
	 * Add a custom field
	 *
	 * @param	integer		$listID			List To create field in 
	 * @param	string		$fieldName		Custom field name
	 */
	public function addCustomField($listID, $fieldName) {
		$custom = 
		$this->OemproApi->customFieldCreate(array(
											'FieldName' => $fieldName,
											'FieldType' => 'Single line',
											'ValidationMethod' => 'Disabled',
											'SubscriberListID' => $listID,
											'Visibility' => 'Public',
											'IsRequired' => 'No',
											'IsUnique' => 'No',
											'IsGlobal' => 'No'));
		if ( ! $custom
			|| empty($custom->Success)) {
			// List creation failed
			$this->lastErrorResult =  "OemproApi customFieldCreate failed";
			return false;
		}
		return $custom->CustomFieldID;		
	}
	
	/**
	 * Delete a custom field
	 *
	 * @param	mixed		$field			Either a single field or an array of fields to delete
	 * @return	boolean		True on success, otherwise false
	 */
	public function deleteCustomField($field) {
		$delete = (is_array($field)) ? $field : array($field);
		$custom = 
		$this->OemproApi->customFieldsDelete(array(
											'CustomFields' => join(',',$delete),
											));
		if ( ! $custom
			|| empty($custom->Success)) {
			$this->lastErrorResult =  "OemproApi customFieldsDelete failed";
			return false;
		}
		return true;	
	}
	
	/**
	 * Add a segment
	 *
	 * @param	integer		$listID			List To create field in 
	 * @param	string		$customFieldId		Custom field ID
	 */
	public function addSegment($listID, $segmentName, $customFieldId) {
		$custom = 
		$this->OemproApi->segmentCreate(array(
											'SubscriberListID' => $listID,
											'SegmentName' => $segmentName,
											'SegmentOperator' => 'and',
											'SegmentRuleField' => array('CustomField'.$customFieldId),
											'SegmentRuleOperator' => array('Is'),
											'SegmentRuleFilter' => array('1'),
											));
		if ( ! $custom
			|| empty($custom->Success)) {
			// List creation failed
			$this->lastErrorResult =  "OemproApi segmentCreate failed";
			return false;
		}
		return $custom->SegmentID;		
	}
	
	/**
	 * Delete a segment field
	 *
	 * @param	mixed		$segmentID			Segment ID to delete or array of segment IDs to delete
	 * @return	boolean		True on success, otherwise false
	 */
	public function deleteSegment($segmentID) {
		$delete = (is_array($segmentID)) ? $segmentID : array($segmentID);
		$custom = 
		$this->OemproApi->segmentsDelete(array(
											'Segments' => join(',',$delete),
											));
		if ( ! $custom
			|| empty($custom->Success)) {
			$this->lastErrorResult =  "OemproApi segmentsDelete failed";
			return false;
		}
		return true;
	}
	
}
?>